import * as React from "react";
import { DatePicker } from "antd";
import moment, { Moment } from "moment";

const RangePicker:any= DatePicker.RangePicker;
export interface DayRangePickerProps {
  day: number;
  onChange: (d: any) => any;
  value: [Moment | null, Moment | null];
}

export interface DayRangePickerState {}

class DayRangePicker extends React.Component<
  DayRangePickerProps,
  DayRangePickerState
> {
  state = {
    startDate: null,
    endDate: null,
  };
  render() {
    return (
      <>
        <RangePicker
          disabledDate={(current: Moment) => {
            return this.disabledDate(current);
          }}
          allowClear={false}
          onCalendarChange={(date: any) => {
            this.setState({
              startDate: date[0] ? date[0].format("YYYY-MM-DD") : null,
              endDate: date[1] ? date[1].format("YYYY-MM-DD") : null,
            });
          }}
          value={this.props.value}
          onChange={(data: any) => {
            this.props.onChange(data);
          }}
        />
      </>
    );
  }
  shouldComponentUpdate(
    newProps: DayRangePickerProps,
    newState: DayRangePickerState
  ) {
    if (newProps.value !== this.props.value) {
      this.setState({
        startDate: newProps.value[0]
          ? newProps.value[0].format("YYYY-MM-DD")
          : null,
        endDate: newProps.value[1]
          ? newProps.value[1].format("YYYY-MM-DD")
          : null,
      });
    }
    return true;
  }
  disabledDate(current: Moment) {
    let startDate: any = this.state.startDate;
    let endDate: any = this.state.endDate;
    let bon: boolean = false;
    if (endDate) {
      bon =
        current &&
        current < moment(endDate).add(-this.props.day, "day").startOf("day");
    }
    if (startDate) {
      bon =
        (current &&
          current >
            moment(startDate).add(this.props.day, "day").endOf("day")) ||
        current < moment(startDate).endOf("day");
    }
    return bon;
  }
}

export default DayRangePicker;
